from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from openpyxl import load_workbook

from app01 import models
from app01.utils.bootstrapForm import BootstrapModelForm


class CityModelForm(BootstrapModelForm):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = '__all__'


@csrf_exempt
def upload_list(request):
    if request.method == 'GET':
        return render(request, 'upload_list.html')
    print(request.POST)
    print(request.FILES)
    file_object = request.FILES.get('uploadFile')
    ff = open(file_object.name, mode='wb')
    for chunk in file_object.chunks():
        ff.write(chunk)
    ff.close()
    return HttpResponse('...')


@csrf_exempt
def upload_multi(request):
    """通过上传excel文件批量新增部门"""
    file_object = request.FILES.get('exc')
    print(file_object)
    wb = load_workbook(file_object)

    sheet = wb.get_sheet_by_name('Sheet1')
    for row in sheet.iter_rows(min_row=2):
        value = row[0].value
        exists = models.Department.objects.filter(title=value).exists()
        if not exists:
            models.Department.objects.create(title=value)
    return redirect('/depart/list/')


def upload_modelform(request):
    title = "modelForm文件上传"
    if request.method == 'GET':
        form = CityModelForm()
        return render(request, 'city_upload.html', {'form': form, 'title': title})
    form = CityModelForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        return redirect('/city/list/')
    return render(request, 'city_upload.html', {'form': form, 'title': title})


def city_list(request):
    queryset = models.City.objects.all()
    return render(request, 'city_list.html', {'queryset': queryset})